/**
 *  Eclipse Public License 1.0
 */
package org.fireblade.easysms;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

/**
 * the main (one and sole) activty
 */
public class MainActivity extends Activity {

  /**
   * constant for shared preferences
   */
  protected static final String EASY_SMS_SP = "EasySMS";
  /**
   * main log tag
   */
  protected static final String EASY_SMS = EASY_SMS_SP + ".";
  /**
   * own log tag
   */
  private static final String LOGTAG = MainActivity.EASY_SMS + MainActivity.class.getSimpleName();

  /** preferences key */
  protected static final String PASSWORD = "password";
  /** preferences key */
  protected static final String LOGINNAME = "loginname";
  /** preferences key */
  protected static final String AUTO_BT = "auto-bt";
  /** preferences key */
  protected static final String AUTO_WIFI = "auto-wifi";
  /** preferences key */
  protected static final String KEEP_WIFI = "keep-wifi";
  /** preferences key */
  protected static final String PORT = "port";
  /** preferences key */
  protected static final String UPDATE_INTERVAL = "updateInterval";
  /** preferences key */
  protected static final String MAX_UNREAD_ID = "maxUnreadId";
  
  /** global flag if donate or not */
  public static final boolean DONATE_VERSION = false;


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(LOGTAG, "onCreate");
    try {
      setContentView(R.layout.layout);
      Button startWifi = (Button) findViewById(R.id.wifionbutton);
      startWifi.setOnClickListener(new Wifi_USBManualListener(Wifi_USBEventReceiver.MANUAL_ON));
      Button stopWifi = (Button) findViewById(R.id.wifioffbutton);
      stopWifi.setOnClickListener(new Wifi_USBManualListener(Wifi_USBEventReceiver.MANUAL_OFF));
      Button startBT = (Button) findViewById(R.id.btonbutton);
      startBT.setOnClickListener(new BluetoothManualListener(Wifi_USBEventReceiver.MANUAL_ON));
      Button stopBT = (Button) findViewById(R.id.btoffbutton);
      stopBT.setOnClickListener(new BluetoothManualListener(Wifi_USBEventReceiver.MANUAL_OFF));

      final Button saveButton = (Button) findViewById(R.id.savebutton);
      saveButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
          saveButton.requestFocus();
          save(view.getContext());
          Toast.makeText(view.getContext(), view.getResources().getString(R.string.str_saved),
            Toast.LENGTH_SHORT).show();
        }
      });

      final EditText port = (EditText) findViewById(R.id.portField);

      port.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean arg1) {
          if (port == arg0) {
            String newText = port.getText().toString();
            if (newText.trim().equals("")) {
              port.setText("2511");
            } else {
              int test = Integer.parseInt(newText);
              if (test <= 1024 || test >= 65535) {
                port.setText("2511");
              }
            }
          }
        }

      });

    } catch (Exception e) {
      Log.e(LOGTAG, "Error onCreate)", e);
      Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
    }
  }


  @Override
  protected void onResume() {
    super.onResume();
    Log.d(LOGTAG, "onResume");
    SharedPreferences pref = getSharedPreferences(EASY_SMS_SP, MODE_PRIVATE);
    CheckBox wifiBox = (CheckBox) findViewById(R.id.autostartwifi);
    CheckBox btBox = (CheckBox) findViewById(R.id.autostartbt);
    EditText login = (EditText) findViewById(R.id.loginField);
    EditText password = (EditText) findViewById(R.id.passwordField);
    EditText port = (EditText) findViewById(R.id.portField);
    EditText updateField = (EditText) findViewById(R.id.updateField);
    CheckBox keepWifi = (CheckBox) findViewById(R.id.keepwifi);
    keepWifi.setChecked(pref.getBoolean(KEEP_WIFI, false));
    wifiBox.setChecked(pref.getBoolean(AUTO_WIFI, true));
    btBox.setChecked(pref.getBoolean(AUTO_BT, true));
    login.setText(pref.getString(LOGINNAME, ""));
    password.setText(pref.getString(PASSWORD, ""));
    port.setText(Integer.toString(pref.getInt(PORT, 2511)));
    updateField.setText(0 != pref.getInt(UPDATE_INTERVAL, 0) ? Integer.toString(pref.getInt(UPDATE_INTERVAL, 0))
      : "");
  }


  @Override
  protected void onPause() {
    super.onPause();
    Log.d(LOGTAG, "onPause");
    save(this);
  }


  protected void save(Context context) {
    Log.d(LOGTAG, "save settings");
    SharedPreferences pref = context.getSharedPreferences(EASY_SMS_SP, MODE_PRIVATE);
    Editor editor = pref.edit();
    CheckBox wifiBox = (CheckBox) findViewById(R.id.autostartwifi);
    CheckBox btBox = (CheckBox) findViewById(R.id.autostartbt);
    EditText login = (EditText) findViewById(R.id.loginField);
    EditText password = (EditText) findViewById(R.id.passwordField);
    EditText port = (EditText) findViewById(R.id.portField);
    EditText update = (EditText) findViewById(R.id.updateField);
    CheckBox keepWifi = (CheckBox) findViewById(R.id.keepwifi);
    editor.putBoolean(KEEP_WIFI, keepWifi.isChecked());
    editor.putBoolean(AUTO_WIFI, wifiBox.isChecked());
    editor.putBoolean(AUTO_BT, btBox.isChecked());
    editor.putString(LOGINNAME, login.getText().toString());
    editor.putString(PASSWORD, password.getText().toString());
    int portInt = 2511;
    try {
      portInt = Integer.parseInt(port.getText().toString().trim());
      if (portInt <= 1024 || portInt >= 65535) {
        port.setText("2511");
      }
    } catch (Exception e) {
      // ignore
    }
    editor.putInt(PORT, portInt);

    int updateInt = 0;
    try {
      updateInt = Integer.parseInt(update.getText().toString().trim());
    } catch (Exception e) {
      // ignore
    }
    editor.putInt(UPDATE_INTERVAL, updateInt);
    editor.commit();
  }
}